package logic

import (
	"cloud-disk/core/helper"
	"context"

	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RefreshAuthorizationLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRefreshAuthorizationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefreshAuthorizationLogic {
	return &RefreshAuthorizationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RefreshAuthorizationLogic) RefreshAuthorization(req *types.ShareBasicSaveRequestRequest, authorization string) (resp *types.ShareBasicSaveRequestResponse, err error) {
	resp = new(types.ShareBasicSaveRequestResponse)
	uc, err := helper.AnalyzeToken(authorization)
	if err != nil {
		resp.Message = err.Error()
		resp.Code = 100
		return resp, nil
	}

	token, err := helper.GenerateToken(uc.Id, uc.Identity, uc.Name, l.svcCtx.Config.TokenExpire)
	if err != nil {
		resp.Message = err.Error()
		resp.Code = 100
		return resp, nil
	}

	// 用户刷新用户认证token的token
	RefreshToken, err := helper.GenerateToken(uc.Id, uc.Identity, uc.Name, l.svcCtx.Config.RefreshTokenExpire)
	if err != nil {
		resp.Message = err.Error()
		resp.Code = 100
		return resp, nil
	}

	resp.Token = token
	resp.Code = 200
	resp.Message = "刷新成功"
	resp.RefreshToken = RefreshToken
	return resp, nil
}
